<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-13
 * Time: 15:34:53
 * Info:
 */

namespace plugin\huiblog\app\controller\module;

use support\Request;
use support\Cache;
use plugin\huiblog\app\model\Config as ConfigModel;

class ConfigController
{

    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $count = ConfigModel::count();
            $data  = ConfigModel::select()->toArray();

            return json(['code' => 0, 'count' => $count, 'data' => $data, 'msg' => 'ok']);
        }

        return view('admin/config/index');
    }

    public function edit(Request $request)
    {
        if ($request->isPost()) {
            $param = $request->post();
            if (empty($param['id'])) {
                return json(['code' => 0, 'msg' => '参数错误']);
            }
            $data            = [];
            $data['content'] = serialize($param);
            ConfigModel::update($data, ['id' => $param['id']]);
            $conf = ConfigModel::find($param['id']);
            Cache::delete('huiblog_config'.$conf['name']);

            return json(['code' => 200, 'msg' => '操作成功']);
        }

        $id  = $request->get('id');
        $res = ConfigModel::find($id);
        if (empty($res)) {
            return json(['code' => 0, 'msg' => '获取数据失败']);
        }
        $template_path = base_path().DIRECTORY_SEPARATOR."plugin".DIRECTORY_SEPARATOR.$request->plugin.DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."view".DIRECTORY_SEPARATOR."index";
        $templateList  = get_dir($template_path);
        $data          = unserialize($res['content']);

        return view('admin/config/'.$res['name'].'_edit', ['data' => $data, 'template' => $templateList]);
    }

}
